package com.controller.base;

import java.util.*;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;

public class MultiMethodControllerUrlHandlerMapping extends AbstractUrlHandlerMapping{
    @SuppressWarnings("unchecked")   
	private  final Map urlMap = new HashMap();
    
    @SuppressWarnings("unchecked")  
    public void setMappings(Properties mappings) {
		this.urlMap.putAll(mappings);
	}
    public void initApplicationContext() throws BeansException {
    	super.initApplicationContext();
        initialUrlMap();
        registerUrlMap();
    }
    
    @SuppressWarnings("unchecked")
	protected void initialUrlMap()throws BeansException{
        Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(getWebApplicationContext(),
                MultiMethodController.class, true, false);
        List controllers = null;
        if(!matchingBeans.isEmpty()){
            controllers = new ArrayList(matchingBeans.values());
            for(int i = 0; controllers != null && i < controllers.size();i++){
                MultiMethodController controller = (MultiMethodController)controllers.get(i);
                Properties urlPros = controller.getUrlMethodmappings();
                Iterator itr = urlPros.keySet().iterator();
                for(;itr.hasNext();){
                    String url = (String)itr.next();
                    urlMap.put(url,controller);
                }
            }
        }
    }
    @SuppressWarnings("unchecked")
	protected void registerUrlMap()throws BeansException{
        if (this.urlMap.isEmpty()){
        	logger.info("Neither 'urlMap' nor 'mappings' set on MultiMethodControllerUrlHandlerMapping");
        }
        else{
        	Iterator itr = this.urlMap.keySet().iterator();
            while (itr.hasNext()){
                String url = (String) itr.next();
                Object handler = this.urlMap.get(url);
                // prepend with slash if it's not present
                if (!url.startsWith("/")){
                    url = "/" + url;
                }
                //注册到...
                registerHandler(url, handler);
            }
            logger.info("start ...");
        }

    }
}
